package com.lovely602.langchain4j.prompt.controller;


import com.lovely602.langchain4j.prompt.entity.LawPrompt;
import com.lovely602.langchain4j.prompt.service.LawAssistant;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 *
 * @author lizhixing
 */
@Slf4j
@RestController
@RequestMapping("/prompt")
public class ChatPromptController {

    @Resource
    private LawAssistant lawAssistant;

    @Resource
    private ChatModel chatModel;

    /**
     * 通过@UserMessage等消息提示聊天
     */
    @GetMapping("/chat01")
    public String chat01(@RequestParam(value = "msg", defaultValue = "你是谁") String msg) {
        return lawAssistant.chat(msg, 100);
    }

    /**
     * 通过结构化注解@StructuredPrompt提示聊天
     */
    @GetMapping("/chat02")
    public String chat02(@RequestParam(value = "msg", defaultValue = "结婚有冷静期吗？") String msg,
                         @RequestParam(value = "legal", defaultValue = "婚姻法") String legal) {
        LawPrompt lawPrompt = new LawPrompt();
        lawPrompt.setQuestion(msg);
        lawPrompt.setLegal(legal);
        return lawAssistant.chat(lawPrompt);
    }

    /**
     * 通过构造提示词模板创建提示词聊天
     */
    @GetMapping("/chat03")
    public String chat03(@RequestParam(value = "msg", defaultValue = "解释一下{{it}}的学习方法") String msg) {

        //1 构造PromptTemplate模板
        PromptTemplate promptTemplate = PromptTemplate.from(msg);
        //2 由PromptTemplate生成Prompt
        Prompt prompt = promptTemplate.apply(Map.of("it", "java"));
        //3 Prompt提示词变成UserMessage
        UserMessage userMessage = prompt.toUserMessage();
        //4 调用大模型
        ChatResponse chatResponse = chatModel.chat(userMessage);

        return chatResponse.aiMessage().text();
    }

}
